import java.awt.*;
import java.awt.event.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import javax.swing.*;
 
public class CapitolReefGUI extends JFrame implements ActionListener
{

	// This is necessary to format the timestamp to iCal specs (Allan)
	public static SimpleDateFormat iCalDateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmm'00'");
	
	// Time related variables (Allan)
	public Calendar cal = new GregorianCalendar();
    public Date timeStamp = cal.getTime();
	public TimeZone timeZone = cal.getTimeZone();
	
	// Get the difference of hours from GMT (Allan)
    public int ZONE_OFFSET = timeZone.getRawOffset();
    public int GMT_Adjust = ZONE_OFFSET / 3600000;
	
	// public variables for other method and modules to access (Allan)
    //edited by Jerry
	public int year = 0;
	public int month = 0;
    public int date = 0;
	public int time = 0;
	public int hour = 0;
	public int minute = 0;
	public int second = 00;
	public int priority = 0;
	public String eventName = "";
	public String eventLocale = "";
	public String filename = "";
	
	public Date startingTime;
	public Date endingTime;
	
	
	
    public CapitolReefGUI(String name) 
    {
        super(name);
        setResizable(false);
        JFrame guiFrame = new JFrame();
        
        //make sure the program exits when the frame closes
        guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        guiFrame.setTitle("Capitol Reef (.ics) Creator");
        
    }
     
    public void addComponentsToPane(final Container pane) 
    {               
        //Options for the JComboBox 
        String[] calendarMonths = {"January", "February", "March", "April"
                      , "May", "June", "July", "August"
                      , "September", "October", "November", "December"};
        
        //Options for the JList
        String[] calendarDays = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"
                      , "11", "12", "13", "14", "15", "16", "17", "18"
                      , "19", "20", "21", "22", "23", "24", "25", "26"
                      , "27", "28", "29", "30", "31"};
        
        //Years
        String[] calendarYears = {"2012", "2013", "2014", "2015"};
        
        //Options for priority box
        String[] priorityBox = {"0% (Free)","25% (Slightly Busy)","50% (Busy)"
        						,"75% (Prefer Not To Meet)","100% (Cannot Schedule Anything)"};

        //Create a button
        JButton createButton = new JButton("Create File");
          
        //The first JPanel contains a Event name
        final JPanel eventPanel = new JPanel();
        JLabel eventLbl = new JLabel("Event Name:");
        final JTextArea event = new JTextArea();
        event.setPreferredSize(new Dimension(300,20));
        eventPanel.add(eventLbl);
        eventPanel.add(event);
        
        //location
        JLabel locLbl = new JLabel("Location:");
        final JTextArea location = new JTextArea();
        location.setPreferredSize(new Dimension(300,20));
        eventPanel.add(locLbl);
        eventPanel.add(location);
        
        //file name
        JLabel fileLabel = new JLabel("Requested File Name:");
        final JTextArea userfileName = new JTextArea("myevent");
        userfileName.setPreferredSize(new Dimension(200, 20));
        eventPanel.add(fileLabel);
        eventPanel.add(userfileName);
        
        
 
        //Second JPanel, with start time
        final JPanel monthPanel = new JPanel();
        JLabel monthLbl = new JLabel("Start Time:");
        
        final JComboBox months = new JComboBox(calendarMonths);
        final JComboBox days = new JComboBox(calendarDays);
        final JComboBox years = new JComboBox(calendarYears);
        final JTextArea startTime = new JTextArea("1500");
        startTime.setPreferredSize(new Dimension(50,20));
        
        monthPanel.add(monthLbl);
        monthPanel.add(months);
        monthPanel.add(days);
        monthPanel.add(years);
        monthPanel.add(startTime);
        
        //Third Jpanel with end time & dates
        final JPanel endmonthPanel = new JPanel();
        JLabel endmonthLbl = new JLabel("End Time:");
        
        final JComboBox endmonths = new JComboBox(calendarMonths);
        final JComboBox enddays = new JComboBox(calendarDays);
        final JComboBox endyears = new JComboBox(calendarYears);
        final JTextArea endTime = new JTextArea("1700");
        endTime.setPreferredSize(new Dimension(50,20));
        
        monthPanel.add(endmonthLbl);
        monthPanel.add(endmonths);
        monthPanel.add(enddays);
        monthPanel.add(endyears);
        monthPanel.add(endTime);
        
        
        final JPanel priorityPanel = new JPanel();
        JLabel priorityLabel = new JLabel("Set Priority");
        
        final JComboBox setPriority = new JComboBox(priorityBox);
        priorityPanel.add(priorityLabel);
        priorityPanel.add(setPriority);
        
        
        //Fourth JPanel with status of event creation
        final JPanel updater = new JPanel();
        JLabel statusUpdater = new JLabel("Event creator status:");
        final JTextArea creatorStatus = new JTextArea("Please enter hours with 24-hour format. "
        												+ "Your event will be outputted to the"
        												+ " file name of your choice.");
        creatorStatus.setPreferredSize(new Dimension(700,20));
        
        updater.add(statusUpdater);
        updater.add(creatorStatus);
        updater.add(createButton);
        
 
         
        pane.add(eventPanel, BorderLayout.NORTH);
        pane.add(monthPanel, BorderLayout.WEST);
        pane.add(priorityPanel, BorderLayout.EAST);
        pane.add(updater, BorderLayout.SOUTH);
        
        // Added by Allan
        //Edited by Jerry
        createButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				try {
					
					// Time Stamp
					Calendar cal = new GregorianCalendar();
				    Date timeStamp = cal.getTime();
					TimeZone timeZone = cal.getTimeZone();
					
					// Get the difference of hours from GMT
				    int ZONE_OFFSET = timeZone.getRawOffset();
				    int GMT_Adjust = ZONE_OFFSET / 3600000;
				    
				    //Get the information from GUI (start of event)
				    eventLocale = location.getText();
				    eventName = event.getText();
					year = Integer.parseInt(years.getSelectedItem().toString());
					month = months.getSelectedIndex();				
					date = days.getSelectedIndex() + 1;
					time = Integer.parseInt(startTime.getText());
					
					//get the hour, minutes, and seconds
					String separateTime = Integer.toString(time);
					hour = Integer.parseInt(separateTime.substring(0,2));
					hour = hour - GMT_Adjust;
					minute = Integer.parseInt(separateTime.substring(2,4));
					
					cal.set(year,month,date,hour,minute,second);
					
					startingTime = cal.getTime();
					
					//Get information from GUI (end of event)
					year = Integer.parseInt(endyears.getSelectedItem().toString());
					month = endmonths.getSelectedIndex();				
					date = enddays.getSelectedIndex() + 1;
					time = Integer.parseInt(endTime.getText());
					
					//get the hour, minutes, and seconds
					separateTime = Integer.toString(time);
					hour = Integer.parseInt(separateTime.substring(0,2));
					hour = hour - GMT_Adjust;
					minute = Integer.parseInt(separateTime.substring(2,4));
					
					cal.set(year,month,date,hour,minute,second);
					
					endingTime = cal.getTime();
					
					int userPriority = setPriority.getSelectedIndex();
					
					switch(userPriority) {
					case 1: priority = 9; break;
					case 2: priority = 5; break;
					case 3: priority = 4; break;
					case 4: priority = 1; break;
					default: priority = 0; break;
					}
					
					
					
					//do the file name with the suffix .ics
					filename = userfileName.getText() + ".ics";
					
					// this string builder is compatible with iCal specifications (we can add more if necessary--Allan)
					//edited by Jerry
					String calendarContent =
					        "BEGIN:VCALENDAR\n" +
					                "METHOD:REQUEST\n" +
					                "PRODID:\n" +
					                "VERSION:2.0\n" +
					                "BEGIN:VEVENT\n" +
					                "DTSTAMP:" + iCalDateFormat.format(timeStamp) + "Z\n" +
					                "DTSTART:" + iCalDateFormat.format(startingTime) + "Z\n" +
					                "DTEND:"  + iCalDateFormat.format(endingTime) + "Z\n" +
					                "SUMMARY:" + eventName + "\n" +
					                "UID:\n" +
					                "ATTENDEE:\n" +
					                "ORGANIZER:MAILTO:organizer@yahoo.com\n" +
					                "LOCATION:" + eventLocale + "\n" +
					                "DESCRIPTION:\n" +
					                "SEQUENCE:0\n" +
					                "PRIORITY:" + priority + "\n" +
					                "CLASS:PUBLIC\n" +
					                "STATUS:CONFIRMED\n" +
					                "TRANSP:OPAQUE\n" +
					                "BEGIN:VALARM\n" +
					                "ACTION:DISPLAY\n" +
					                "DESCRIPTION:REMINDER\n" +
					                "TRIGGER;RELATED=START:-PT00H15M00S\n" +
					                "END:VALARM\n" +
					                "END:VEVENT\n" +
					                "END:VCALENDAR";

						// We can list the file contents with this next line
						System.out.println(calendarContent);
						
						//Update status of event creation
						creatorStatus.setText("Creation of event: \"" + eventName + "\" was a success!");
						
						// File output section  	
					  	FileWriter fw = new FileWriter(filename);
					  	BufferedWriter bw = new BufferedWriter(fw);
					  	PrintWriter outFile = new PrintWriter(bw);
					  
					  	// Produces a file 
					  	outFile.println(calendarContent);
					  
					  	// Close file stream
					  	outFile.close();
					
				}
				catch (Exception e) {
					creatorStatus.setText("There was an error in your information.  Please enter it again!");
				}
			}
        });
    }
     
    /**
     * Create the GUI and show it.  For thread safety,
     * this method is invoked from the
     * event dispatch thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        CapitolReefGUI frame = new CapitolReefGUI("Capitol Reef Team .ICS Creator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Set up the content pane.
        frame.addComponentsToPane(frame.getContentPane());
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
     
    public static void main(String[] args) {
        /* Use an appropriate Look and Feel */
        try {
            //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
        } catch (UnsupportedLookAndFeelException ex) {
            ex.printStackTrace();
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        } catch (InstantiationException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }

        //Schedule a job for the event dispatch thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
       	
        }


    
    // Added by Allan
	@Override
	public void actionPerformed (ActionEvent event) {
	
		
	}


}
